<script setup lang="ts">
import { useStorage } from '@vueuse/core'
import { computed } from 'vue'
import { liftStatusItemA, liftStatusItemB } from '@/utils/liftStatusItem'
import { instance } from '@/utils/request'
import { ElMessageBox, ElNotification, dayjs } from 'element-plus'
import { useLoadingStore } from '@/store/loading'

const loc = import.meta.env.VITE_LOC

const { toggleLoading } = useLoadingStore()

const { liftID } = defineProps(['liftID'])

const liftStatus = useStorage('lift-status', [])

const currentLift = computed(() => {
  if (liftID === 6) {
    return liftStatus.value[0]
  } else {
    return liftStatus.value[1]
  }
})

const getContent = (prop, val) => {
  if (prop === 'status') {
    // 控制模式
    const map = {
      '0': ['未就绪', 'danger'],
      '1': ['异常', 'danger'],
      '2': ['手动运行中', 'warning'],
      '3': ['手动等待指令', 'warning'],
      '4': ['自动运行中', 'success'],
      '5': ['自动等待指令', 'success'],
      '6': ['现场手动模式', 'warning'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (prop === 'platStatus') {
    // 升降 Z 轴
    const map = {
      '1': ['安全位', 'success'],
      '2': ['CCD 校准位', 'warning'],
      '3': ['取罐位', 'warning'],
      '4': ['取罐下方位', 'warning'],
      '5': ['注液位', 'warning'],
      '99': ['不在点位', 'danger'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (prop === 'clampStatus') {
    // 夹紧 X 轴
    const map = {
      '17': ['安全位', 'success'],
      '18': ['CCD 校准位', 'warning'],
      '19': ['取罐位', 'warning'],
      '99': ['不在点位', 'danger'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (prop === 'restorationStatus') {
    // AGV 踏板轴
    const map = {
      '33': ['打开位', 'warning'],
      '34': ['关闭位', 'success'],
      '99': ['不在点位', 'danger'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (String(prop).includes('valve')) {
    // 注液 AB 阀
    const map = {
      '1': ['关闭位', 'warning'],
      '2': ['打开位', 'success'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (String(prop).includes('open')) {
    // 注液 AB 轴
    return !val ? (Number(currentLift.value?.[prop]) * 100).toFixed(0) + ' %' : 'success'
  } else if (prop === 'clampStatus1') {
    // 清洗架
    const map = {
      '1': ['打开位', 'success'],
      '2': ['关闭位', 'success'],
      '99': ['不在点位', 'danger'],
    }
    return map[currentLift.value?.[prop]]?.[val]
  } else if (prop === 'weight') {
    // 当前重量
    if (Number(currentLift.value?.[prop]) < 1) {
      return !val ? (0).toFixed(2) + ' KG' : 'success'
    } else {
      return !val ? Number(currentLift.value?.[prop]).toFixed(2) + ' KG' : 'success'
    }
  } else if (prop === 'targetWeight') {
    // 目标重量
    return !val ? Number(currentLift.value?.[prop]).toFixed(2) + ' KG' : 'success'
  } else if (prop === 'updateTime') {
    // 更新时间
    return !val ? dayjs(currentLift.value?.[prop]).format('YY-MM-DD HH:mm:ss') : 'success'
  } else {
    return !val ? '未知' : 'danger'
  }
}

const getLiftStatus = (val) => {
  if (liftID === 6) {
    return liftStatusItemA[Number(val)]
  } else {
    return liftStatusItemB[Number(val)]
  }
}

const tubeControl = async (code) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/agv/artificial`,
      method: 'get',
      params: { id: liftID, code },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const modeControl = async (code) => {
  if (code !== 1) {
    await ElMessageBox.confirm('请确认是否继续操作', '警告')
  }
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/lift`,
      method: 'get',
      params: { id: liftID, code },
    })
    ElNotification({ type: 'success', title: [3, 4].includes(code) ? '模式切换成功' : '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const remoteControl = async (code) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/device`,
      method: 'get',
      params: { id: liftID, code },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const checkCCD = async (point) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    const { message } = (await instance({
      url: `/remote/v1/check/ccd`,
      method: 'get',
      params: { point },
    })) as any
    ElNotification({ type: 'success', title: '指令发送成功', message })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const automaticTask = async (code) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/semi/automatic/task`,
      method: 'get',
      params: { id: liftID, code },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const deliverWeight = async () => {
  const { value } = await ElMessageBox.prompt('请输入需要下发的重量，单位KG', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /^[1-9]\d*(.\d{1,2})?$/,
    inputErrorMessage: '输入数字格式有误',
  })
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/deliver/weight`,
      method: 'get',
      params: { id: liftID, weight: value },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

/**
 * 夹紧 X 轴安全互锁
 */
const xAxisLock = computed(() => {
  /**
   * 判断升降台控制模式是否为手动等待指令
   */
  if (currentLift.value.status === '3') {
    /**
     * 判断升降 Z 轴是否在安全位或取罐位下方位
     */
    if (['1', '4'].includes(currentLift.value.platStatus)) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
})
</script>

<template>
  <div class="common w-auto h-auto text-#96d8ff flex flex-col gap-3 relative">
    <div class="title">{{ liftID === 6 ? '取料升降台' : '放料升降台' }}</div>
    <div v-if="loc === '375'" class="absolute top-3 left-3 flex gap-1">
      <ElTag size="small">温度:{{ currentLift.temperature }}°C</ElTag>
      <ElTag size="small">湿度:{{ currentLift.humidity }}%</ElTag>
    </div>
    <div class="absolute top-4 right-4">
      <ADropdown position="br">
        <ElButton color="#4e648763" class="p-2"><i class="i-icons:menu text-16px mb-0.5" /></ElButton>
        <template #content>
          <ADoption @click="deliverWeight()">下发任务重量</ADoption>
          <ADoption @click="checkCCD(liftID)">升降台 CCD 校准</ADoption>
          <ADoption v-if="liftID === 6" @click="checkCCD(4)">清洗区 CCD 校准</ADoption>
          <ADsubmenu>
            <template #default>半自动任务</template>
            <template #content>
              <ADoption v-if="liftID === 6" @click="automaticTask(3)">1344升降台取料准备</ADoption>
              <ADoption v-if="liftID === 6" @click="automaticTask(6)">1344升降台放罐前自检</ADoption>
              <ADoption v-if="liftID === 6" @click="automaticTask(7)">1344升降台放罐动作</ADoption>
              <ADoption v-if="liftID === 6" @click="automaticTask(1)">1344升降台取罐前自检</ADoption>
              <ADoption v-if="liftID === 6" @click="automaticTask(2)">1344升降台取罐动作</ADoption>
              <ADoption v-if="liftID === 8" @click="automaticTask(17)">1108升降台取罐前自检</ADoption>
              <ADoption v-if="liftID === 8" @click="automaticTask(18)">1108升降台取罐动作</ADoption>
              <ADoption v-if="liftID === 8" @click="automaticTask(19)">1108升降台放料准备</ADoption>
              <ADoption v-if="liftID === 8" @click="automaticTask(22)">1108升降台放罐前自检</ADoption>
              <ADoption v-if="liftID === 8" @click="automaticTask(23)">1108升降台放罐动作</ADoption>
            </template>
          </ADsubmenu>
        </template>
      </ADropdown>
    </div>
    <div
      class="grid grid-rows-4 [&>div]:self-center gap-2"
      :class="[`${liftID === 6 ? 'grid-cols-[200px_180px_1fr]' : 'grid-cols-[220px_1fr]'}`]"
    >
      <div class="flex items-center">
        <div class="w-24 text-right">升降 Z 轴：</div>
        <ElTag :type="getContent('platStatus', 1)">{{ getContent('platStatus', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">注液 1# 轴：</div>
        <ElTag :type="getContent('open1', 1)">{{ getContent('open1', 0) }}</ElTag>
      </div>
      <div class="flex items-center">
        <div class="w-24 text-right">实时重量：</div>
        <ElTag :type="getContent('weight', 1)">{{ getContent('weight', 0) }}</ElTag>
      </div>
      <div class="flex items-center">
        <div class="w-24 text-right">夹紧 X 轴：</div>
        <ElTag :type="getContent('clampStatus', 1)">{{ getContent('clampStatus', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">注液 1# 阀：</div>
        <ElTag :type="getContent('valve1', 1)">{{ getContent('valve1', 0) }}</ElTag>
      </div>
      <div class="flex items-center">
        <div class="w-24 text-right">目标重量：</div>
        <ElTag :type="getContent('targetWeight', 1)">{{ getContent('targetWeight', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">AGV 踏板：</div>
        <ElTag :type="getContent('restorationStatus', 1)">{{ getContent('restorationStatus', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">注液 2# 轴：</div>
        <ElTag :type="getContent('open', 1)">{{ getContent('open', 0) }}</ElTag>
      </div>
      <div class="flex items-center">
        <div class="w-24 text-right">控制模式：</div>
        <ElTag :type="getContent('status', 1)">{{ getContent('status', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">清洗架：</div>
        <ElTag :type="getContent('clampStatus1', 1)">{{ getContent('clampStatus1', 0) }}</ElTag>
      </div>
      <div v-if="liftID === 6" class="flex items-center">
        <div class="w-24 text-right">注液 2# 阀：</div>
        <ElTag :type="getContent('valve', 1)">{{ getContent('valve', 0) }}</ElTag>
      </div>
      <div class="flex items-center">
        <div class="w-24 text-right">更新时间：</div>
        <ElTag :type="getContent('updateTime', 1)">{{ getContent('updateTime', 0) }}</ElTag>
      </div>
      <div class="flex items-center" :class="[liftID === 6 ? 'col-span-3' : 'col-span-2']">
        <div class="w-24 text-right">当前状态：</div>
        <ElTag :class="[liftID === 6 ? 'w-131' : 'w-89']">{{ getLiftStatus(currentLift.message) }}</ElTag>
      </div>
    </div>
    <div class="grid grid-rows-2 gap-2" :class="{ 'grid-cols-5': liftID === 6, 'grid-cols-4': liftID === 8 }">
      <ElDropdown v-if="liftID === 6">
        <ElButton class="w-full" type="primary" plain>注液 1# 罐</ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem @click="tubeControl(9)" :disabled="currentLift.message !== '22'">
              确认插管完成
            </ElDropdownItem>
            <ElDropdownItem @click="tubeControl(10)" :disabled="currentLift.message !== '24'">
              确认拔管完成
            </ElDropdownItem>
            <ElDropdownItem @click="remoteControl(67)" :disabled="currentLift.status !== '3'">
              气阀打开
            </ElDropdownItem>
            <ElDropdownItem @click="remoteControl(68)" :disabled="currentLift.status !== '3'">
              气阀关闭
            </ElDropdownItem>
            <ElDropdownItem @click="remoteControl(72)" :disabled="currentLift.status !== '3'">
              电机阀打开
            </ElDropdownItem>
            <ElDropdownItem @click="remoteControl(71)" :disabled="currentLift.status !== '3'">
              电机阀关闭
            </ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
      <ElDropdown>
        <ElButton v-if="liftID === 6" class="w-full" type="primary" plain>注液 2# 罐</ElButton>
        <ElButton v-if="liftID === 8" class="w-full" type="primary" plain>放液 A 阀</ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <template v-if="liftID === 6">
              <ElDropdownItem @click="tubeControl(4)" :disabled="currentLift.message !== '22'">
                确认插管完成
              </ElDropdownItem>
              <ElDropdownItem @click="tubeControl(5)" :disabled="currentLift.message !== '24'">
                确认拔管完成
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(65)" :disabled="currentLift.status !== '3'">
                气阀打开
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(66)" :disabled="currentLift.status !== '3'">
                气阀关闭
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(70)" :disabled="currentLift.status !== '3'">
                电机阀打开
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(69)" :disabled="currentLift.status !== '3'">
                电机阀关闭
              </ElDropdownItem>
            </template>
            <template v-if="liftID === 8">
              <ElDropdownItem @click="tubeControl(20)" :disabled="currentLift.message !== '22'">
                确认插管完成
              </ElDropdownItem>
              <ElDropdownItem @click="tubeControl(21)" :disabled="currentLift.message !== '24'">
                确认拔管完成
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(81)" :disabled="currentLift.status !== '3'">
                气阀打开
              </ElDropdownItem>
              <ElDropdownItem @click="remoteControl(82)" :disabled="currentLift.status !== '3'">
                气阀关闭
              </ElDropdownItem>
            </template>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
      <ElDropdown>
        <ElButton class="w-full" type="primary" plain>模式切换</ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem @click="modeControl(3)">手动模式</ElDropdownItem>
            <ElDropdownItem @click="modeControl(4)">自动模式</ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
      <div>
        <ElButton class="w-full" type="danger" plain @click="modeControl(5)">设备停止</ElButton>
      </div>
      <div class="row-span-2">
        <ElButton class="w-full h-full text-28px font-bold" type="danger" @dblclick="modeControl(1)">急停</ElButton>
      </div>
      <ElDropdown :disabled="currentLift.status !== '3'">
        <ElButton class="w-full" type="primary" plain :disabled="currentLift.status !== '3'">升降 Z 轴</ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem @click="remoteControl(1)">安全位</ElDropdownItem>
            <ElDropdownItem @click="remoteControl(3)">取罐位</ElDropdownItem>
            <ElDropdownItem @click="remoteControl(4)">取罐下方位</ElDropdownItem>
            <ElDropdownItem
              v-if="liftID === 6"
              @click="remoteControl(5)"
              :disabled="currentLift.restorationStatus === '34'"
            >
              注液位
            </ElDropdownItem>
            <ElDropdownItem v-if="liftID === 8" @click="remoteControl(5)">放液位</ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
      <ElDropdown :disabled="!xAxisLock">
        <ElButton class="w-full" type="primary" plain :disabled="!xAxisLock"> 夹紧 X 轴 </ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem @click="remoteControl(17)">安全位</ElDropdownItem>
            <ElDropdownItem @click="remoteControl(19)">取罐位</ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
      <div v-if="liftID === 6" class="flex justify-between">
        <ElDropdown :disabled="currentLift.status !== '3'">
          <ElButton class="w-50px" type="primary" plain :disabled="currentLift.status !== '3'">踏板</ElButton>
          <template #dropdown>
            <ElDropdownMenu>
              <ElDropdownItem @click="remoteControl(33)">打开踏板</ElDropdownItem>
              <ElDropdownItem :disabled="currentLift.platStatus !== '1'" @click="remoteControl(34)">
                关闭踏板
              </ElDropdownItem>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
        <ElDropdown :disabled="currentLift.status !== '3'">
          <ElButton class="w-60px" type="primary" plain :disabled="currentLift.status !== '3'">清洗架</ElButton>
          <template #dropdown>
            <ElDropdownMenu>
              <ElDropdownItem @click="remoteControl(49)">打开支架</ElDropdownItem>
              <ElDropdownItem @click="remoteControl(50)">关闭支架</ElDropdownItem>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
      </div>
      <div>
        <ElButton class="w-full" type="warning" plain @click="modeControl(2)">设备复位</ElButton>
      </div>
    </div>
  </div>
</template>
